'use strict'

const Service = require('egg').Service

class StaffService extends Service {
  async getStaffList(queryInfo) {
    // 初始化 queryInfo 处理未传参数情况
    queryInfo = {
      keywords: queryInfo.keywords || '',
      pageNum: queryInfo.pageNum || 1,
      pageSize: queryInfo.pageSize || 10,
    }

    let resultAll = await this.app.mysql.query(
      'select count(*) as totalnum from c_staff WHERE staffname like ?',
      ['%' + queryInfo.keywords + '%']
    )

    let result = await this.app.mysql.query(
      `SELECT
      u.id,
      u.staffname,
      u.department_id,
      d.departname,
      u.duty,
      u.safetyduty,
      u.phone,
      u.identitycardid,
      u.sex 
    FROM
      c_staff AS u
      LEFT JOIN c_department AS d ON u.department_id = d.id 
    WHERE
      u.staffname LIKE ? 
      LIMIT ?,?`,
      [
        '%' + queryInfo.keywords + '%',
        parseInt(queryInfo.pageNum - 1) * queryInfo.pageSize,
        parseInt(queryInfo.pageSize),
      ]
    )
    return {
      data: {
        total: resultAll[0].totalnum,
        staffList: result,
      },
      meta: {
        msg: '获取成功',
        status: 200,
      },
    }
  }

  async getSingleStaff(identitycardid) {
    const result = await this.app.mysql.select('c_staff', {
      where: {
        identitycardid: identitycardid,
      },
    })
    return this.ctx.getRESTfulData(result, '获取单个员工数据成功', 200)
  }

  async createStaff(staffInfo) {
    const singleResult = await this.getSingleStaff(staffInfo.identitycardid)

    if (singleResult.data.length > 0) {
      return this.ctx.getRESTfulData(null, '该员工的身份证号已存在', 401)
    }

    let result = await this.app.mysql.query(
      'INSERT INTO c_staff (staffname,department_id,duty,safetyduty,phone,identitycardid,sex) VALUES (?,?,?,?,?,?,?)',
      [
        staffInfo.staffname,
        staffInfo.department_id,
        staffInfo.duty,
        staffInfo.safetyduty,
        staffInfo.phone,
        staffInfo.identitycardid,
        staffInfo.sex,
      ]
    )

    return this.ctx.getRESTfulData(result, '员工添加成功', 201)
  }
  async createManyStaff(staffList) {
    try {
      // 记录成功条数
      let successNum = 0
      // 记录未成功信息
      let failedList = []

      for (const key in staffList) {
        if (staffList.hasOwnProperty(key)) {
          const item = staffList[key]

          // 验证要导入的用户是否存在，存在则不导入当前项
          const existStaffListObj = await this.ctx.service.managerrecord.staff.getSingleStaff(
            item.identitycardid
          )
          if (existStaffListObj.data.length > 0) {
            failedList.push(item)
            continue
          }

          // 搜索到 dapartname 对应的 id
          const departResult = await this.ctx.service.managerrecord.department.getSingleDepartment(
            {
              departname: item.departname,
            }
          )

          // 删除 不能插入到该表的 字段
          delete item.departname

          const result = await this.app.mysql.insert('c_staff', {
            ...item,
            department_id: departResult.data[0].id,
          })
          if (result.affectedRows === 1) {
            successNum++
          }
        }
      }

      return this.ctx.getRESTfulData(
        {
          failedList,
        },
        `用户批量添加成功: ${successNum} 条，失败：${failedList.length} 条：身份证已存在`,
        201
      )
    } catch (error) {
      console.log(error)
      return this.ctx.getRESTfulData({ error }, '添加出错', 401)
    }
  }

  async updateStaff(staffInfo, staffId) {
    delete staffInfo.departname
    delete staffInfo.status

    let result = await this.app.mysql.update('c_staff', {
      ...staffInfo,
      id: staffId,
    })
    if (result.affectedRows === 1) {
      return {
        data: result,
        meta: {
          msg: '用户更新成功',
          status: 201,
        },
      }
    }
  }
  async deleteStaff(staffId) {
    let result = await this.app.mysql.delete('c_staff', {
      id: staffId,
    })
    if (result.affectedRows === 1) {
      return {
        data: result,
        meta: {
          msg: '用户删除成功',
          status: 200,
        },
      }
    }
  }
}

module.exports = StaffService
